package com.financing.controller.system;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.financing.model.Data;
import com.financing.model.system.AssetsLog;
import com.financing.model.system.Notice;
import com.financing.model.system.NoticeLog;
import com.financing.model.user.User;
import com.financing.service.system.AssetsLogService;
import com.financing.service.system.NoticeLogService;
import com.financing.service.system.NoticeService;
import com.financing.util.Json;
import com.financing.util.Str;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

public class NoticeController extends Controller {
	private static NoticeService notice = new NoticeService();
	private static AssetsLogService assetsLog = new AssetsLogService();	
	private static NoticeLogService noticeLog = new NoticeLogService();
	
	/**
	 *  获取未阅读的数量
	 */
	public void unReadMark() {
		User u = getAttr("user");
		String type = getPara("type","app");
		long activityNum = noticeLog.unReadNum(type+"_activity", u);
		long newsNum = noticeLog.unReadNum(type+"_news", u);
		long noticeNum = noticeLog.unReadNum(type+"_notice", u);
		long assetsNum = assetsLog.unReadNum(u);
		long total = activityNum + newsNum + noticeNum + assetsNum;
		
		Notice n1 = notice.findByType(type+"_activity",u);
		Notice n2 = notice.findByType(type+"_news",u);
		Notice n3 = notice.findByType(type+"_notice",u);
		AssetsLog n4 = assetsLog.findByType(u.getId()); 
		if(n4!=null) {
			n4.put("summary", n4.getContents());
		}
		renderJson(Json.ok("数据获取成功！", 
			Data.put("total",total, "activity_num", activityNum, "news_num",newsNum, 
			"notice_num",noticeNum, "assets_num",assetsNum,"activity",n1,"news",n2,"notice",n3,"assets",n4)));
	}	
	
	/**
	 *  获取列表公告
	 */
	public void list() {
		User u = getAttr("user");
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		String source = getPara("source","app");
		Map<String, String> params = Data.flat(getParaMap());
		if(Str.eq("assets", getPara("type"))){  
			params.put("userId", String.valueOf(u.getId()));
			Page<AssetsLog> p = assetsLog.list(page, size, params);
			renderJson(Json.ok("数据获取成功！", Data.put("page", p)));
		}else{ 
			if(Str.eq("app", source)) {
				params.put("status", "enable");
			}
			Page<Notice> p = notice.list(page, size, params);
			p.getList().forEach(n->{
				n.put("is_read", noticeLog.isRead(n.getId(), u.getId()) ? 1 : 0);
			});
			renderJson(Json.ok("数据获取成功！", Data.put("page", p)));
		}
	}	
	
	/**
	 *  已阅读该内容
	 */
	public void setRead() {
		User u = getAttr("user"); 
		String ids = getPara("id");
		if(Str.nb(ids)) {
			if(Str.eq("assets", getPara("type",""))){
				for(String id : ids.split(",")) {
					AssetsLog log = AssetsLog.me.findById(id);
					if(Str.eq("user", getPara("role","user"))){
						log.setIsRead(1).update();
					}else{
						if(u.getId().equals(log.getAgentId())) {
							log.setAgentIsRead(1).update();
						} else {
							renderJson(Json.error("仅客服本人可修改状态！"));
							return ;
						}
					}
				}
			}else{
				for(String id : ids.split(",")) {
					// 判断是否已经读过
					if(!noticeLog.isRead(Integer.valueOf(id), u.getId())){
						NoticeLog nl = new NoticeLog();
						nl.setNoticeId(getParaToInt("id"));
						nl.setUserId(u.getId());
						nl.setCreateTime(new Date());
						nl.save();
					}
				} 
			}
			renderJson(Json.ok("数据保存成功！"));
		} else {
			renderJson(Json.error("数据不可为空！"));
		}
	}

	
	/**
	 *  全部阅读该内容
	 */
	public void setAllRead() {
		User u = getAttr("user"); 
		String type = getPara("type","");
		if(Str.eq("assets", type)){
			assetsLog.setAllRead(u);
		}else{
			for(Notice n : noticeLog.unRead(type, u)) {
				NoticeLog nl = new NoticeLog();
				nl.setNoticeId(n.getId());
				nl.setUserId(u.getId());
				nl.setCreateTime(new Date());
				nl.save();
			}
		} 
		renderJson(Json.ok("数据处理成功！"));
	}
	
	/**
	 *  删除记录
	 */
	public void delLog() {
		User u = getAttr("user"); 
		String ids = getPara("id");
		if(Str.nb(ids)){
			if(Str.eq("assets", getPara("type",""))){
				for(String id : ids.split(",")) {
					AssetsLog log = AssetsLog.me.findById(id);
					if(log.getUserId()==u.getId()) {
						log.delete();
					}
				}
			}else{
				for(String id : ids.split(",")) {
					AssetsLog log = AssetsLog.me.findById(id);
					if(log.getUserId()==u.getId()) {
						NoticeLog.me.findById(id).delete();
					}
				}
			}
			renderJson(Json.ok("数据删除成功！"));
		}else{
			renderJson(Json.error("数据不可为空！"));
		}
	}
	
	/**
	 *  模糊搜索
	 */
	public void search() {
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		Page<Notice> p = notice.findByKey(page, size, getPara("key",""));
		renderJson(Json.ok("数据获取成功！", Data.put("page",p)));
	}
	
	/**
	 * 编辑消息
	 */
	public void edit() {
		User u = getAttr("user");
		Date d = new Date(); 
		int id = getParaToInt("id",0);
		Notice notice = id>0 ? Notice.me.findById(id) : new Notice();
		notice.setName(getPara("name"));
		notice.setType(getPara("type"));
		notice.setPic(getPara("pic"));
		notice.setPcPic(getPara("pc_pic"));
		notice.setStatus(getPara("status"));
		notice.setContents(getPara("contents"));
		notice.setSummary(getPara("summary"));
		notice.setUserId(u.getId());
		 
		if(id>0?notice.update():notice.setCreateTime(d).save()) {
			renderJson(Json.ok("信息编辑成功！"));
		}
	}
	
	/**
	 *  获取公告信息
	 */
	@Clear
	public void info() {
		renderJson(Json.ok("数据获取成功！", Notice.me.findById(getParaToInt("id",0))));
	}
	
	/**
	 * 获取系统用户协议
	 */ 
	@Clear
	public void statement() throws Exception {
		String type = getPara("type","riskWarn");
		int id = 0; 
		switch(type){
			case "riskWarn": id=1;break;	// 风险提示函
			case "aboutUs": id=2;break;	// 关于我们
			case "openAccount": id=3;break;	// 开户说明
			case "userAgreement": id=4;break;	// 用户协议
			case "depository": id=5;break;	// 银行存管
			case "security": id=6;break;	// 资金安全
			case "protect": id=7;break;	// 信息保护
			case "control": id=8;break;		// 风控体系
			case "commit": id=9;break;	// 投资人承诺书
		}
        renderJson(Json.ok("获取系统公告成功！", Data.put("item", Notice.me.findById(id))));
	}

	/**
	 *  公告上线/下线
	 */
	public void switchStatus() {
		Notice n = Notice.me.findById(getParaToInt("id",0));
		if(n!=null){
			n.setStatus(getPara("status")).update();
			renderJson(Json.ok("状态修改成功！"));
		}
	}
	
	/**
	 * 公告删除
	 */
	public void del() {
		Notice n = Notice.me.findById(getParaToInt("id",0));
		if(n!=null){
			n.delete();
			renderJson(Json.ok("删除成功！"));
		}
	}	
	
	/**
	 *  帮助中心目录
	 */
	@Clear 
	public void help() {
		List<Notice> categories = notice.categories();
		categories.forEach(n->{
			n.put("list", notice.findByCategory(n.getStr("category")));
		});
		renderJson(Json.ok("数据获取成功！", 
			Data.put("categories",categories,"summary","投资由风险，请用户认证阅读常见问题以及旺进财公布的其他文件，请确认您的风险承担能力、确认已从旺进财获得令您满意的咨询结果、确认拟进行的交易安全以及可能存在的风险之后再进行投资操作。")));
	}	
}
 